import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;


@WebServlet("/blog_delete")
public class BlogDeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取当前登录的用户 session中获取
        HttpSession session= req.getSession(false);
        if(session==null){
            resp.getWriter().write("当前未登录");
            resp.setStatus(302);
            resp.sendRedirect("login.html");
            return;
        }
        User user=(User)session.getAttribute("user");
        if(user==null){
            resp.getWriter().write("当前未登录");
            resp.setStatus(302);
            resp.sendRedirect("login.html");
            return;
        }


        //获取blogId -》 Blog对象 -》userId
        String getBlogId=req.getParameter("blogId");
        if(getBlogId==null){
            return;
        }
        int blogId=Integer.parseInt(getBlogId);
        BlogDao blogDao=new BlogDao();
        try {
            Blog blog=blogDao.selectOne(blogId);
            if(blog==null){
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("该博客不存在");
                resp.setStatus(403);
                return;

            }
            int userId=blog.getUserId();




            if(user.getUserId()==blog.getUserId()){
                blogDao.delete(blogId);
                resp.getWriter().write("删除成功");
                resp.setStatus(302);
                resp.sendRedirect("blog_list.html");
                return;
            }else{

                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("非博客作者，无权限");
                resp.setStatus(403);

            }



        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
